/**
 *
 */
var PanEditor = (function () {
    // 初始化

    function PanEditor(options) { // 属性
        this.panid = options.panid;

        this.zoom = 1.0;
        this.count = 0;
        //当前窗口有的组件个数
        this.controls = [];
        this.dm;
        this.init(options);
        this.initdrag();
    }
    //定时执行保存任务
    PanEditor.prototype.autosave = function (options) {
        var that = this;
        setInterval(function () {
            that.saveeditor();
            console.info("自动保存完成！");
        }, 5000);
    }

    // 初始化
    PanEditor.prototype.init = function (options) {
        var that = this;

        //加载内容
        if (options.tempid) {
            this.loadeditor({ "panid": options.tempid });
        } else {
            this.loadeditor({ "panid": options.panid });
        }


        
        /*初始化编辑*/
        this.dragresize = new DragResize('dragresize', {
            //minWidth: 192,
            //minHeight: 108,
            //minLeft: 0,
            //minTop: 0,
            maxLeft: 1920,
            maxTop: 1080
        });
        
        this.dragresize.isElement = function (elm) {
            if (elm.className && elm.className.indexOf('drsElement') > -1)
                return true;
        };
        this.dragresize.isHandle = function (elm) {
            if (elm.className && elm.className.indexOf('drsMoveHandle') > -1)
                return true;
        };
        
        this.dragresize.ondragfocus = function (e) {
            console.info(e);
            var controle = $(e).find(".dragresize-content");
            var pageurl = JSON.parse($(controle).attr("data")).type;
            
            // $(".loadbox").load('static/app/liujb/templet/' + pageurl + '.html');
            $.getJSON('widget/list/' + pageurl + '.json', function (data) {
                //构建一个边界界面的模板
                var htmls = that.createtools(data.ui);
                $(".loadbox").html(htmls);
                //数据绑定一次
            });
        };
        this.dragresize.ondragstart = function (isResize) { };
        this.dragresize.ondragmove = function (isResize) { };
        this.dragresize.ondragend = function (isResize) {
            if (isResize) {
                $.each(that.controls, function (i, val) {
                    val.tclass.resize();
                });
            }
        };
        this.dragresize.ondragblur = function (e) {
            setTimeout(function () {
                if (that.dragresize.element) {
                    //
                } else {
                    
                    $(".loadbox").load('static/app/liujb/templet/backimg.html', function (ei) {
                        //截取背景图片
                        $("#btntitleimg").on("click", function (e) {
                            that.uploadcanvas();
                        });
                        
                        //文件上传
                        $("#backimgfile").on("change", function () {
                            var filePath = $(this).val();
                            if (filePath.indexOf("jpg") != -1 || filePath.indexOf("png") != -1) {
                                //设置真正工作区比例
                                var file = document.getElementById("backimgfile")
                                var formData = new FormData();
                                formData.append('file', file.files[0]);
                                //formData.append('panid', that.panid);
                                $.ajax({
                                    url: 'pans/uploadfile?panid=' + that.panid,
                                    type: 'POST',
                                    data: formData,
                                    // async: false,
                                    cache: false,
                                    contentType: false,
                                    processData: false,
                                    success: function (data) {
                                        if (200 === data.code) {
                                            $('#result').html("上传成功！");
                                            $('#img').attr('src', data.data);
                                        } else {
                                            $('#result').html("上传失败！");
                                        }
                                        console.log('imgUploader upload success');
                                    },
                                    error: function () {
                                        $("#result").html("与服务器通信发生错误");
                                    }
                                });
                            }
                        })
                    });
                }
            }, 100);


        };
        
        this.dragresize.apply(document.getElementById("workcenter"));

        /*初始化编辑*/
        if ($(".js-min-max-start").length > 0) {

            var dec = document.querySelector('.js-min-max-start');
            var initDec = new Powerange(dec, { decimal: true, callback: displayDecimalValue, min: 30, max: 100, start: 53 });

            function displayDecimalValue() {
                var zoomNum = dec.value / 100;
                that.setzoom(zoomNum);
                try {
                    that.dm.zoom = (zoomNum);
                    // console.info(that.paneditor.dragresize.zoom);
                }
                catch (ex) {
                    console.info(ex);
                }
            }
        }
        //that.autosave();
        //选中空间
        $("#layers li input").change(function () {
            // alert("checked");
            var ddd = $($("#vpc3cd").prop("outerHTML"))[0];
            that.dragresize.select(ddd);
        });
        //顶部工具条
        $(".header ol li").on("click", function (e) {
            var data = JSON.parse($(this).attr("data"));
            if (data.type === "save") {
                that.saveeditor();
            }
        });
    }

    PanEditor.prototype.saveeditor = function (options) {
        var that = this;
        var pandatas = [];


        $.each(that.controls, function (i, val) {
            val.postion = {
                left: $("#" + val.id + "cd").css("left"),
                top: $("#" + val.id + "cd").css("top"),
                width: $("#" + val.id + "cd").css("width"),
                height: $("#" + val.id + "cd").css("height")
            };
            val.zindex = $("#" + val.id + "cd").css("z-index");
            //

            pandatas.push({
                "id": val.id,
                "type": val.type,
                "data": {},
                "content": val.content,
                "zindex": val.zindex,
                "postion": {
                    "left": val.postion.left,
                    "top": val.postion.top,
                    "width": val.postion.width,
                    "height": val.postion.height
                },

            });
        })


        var pandata = {
            "panid": that.panid,
            "panname": "sgx",
            "pancount": that.count,
            "userid": "admin",
            "content": JSON.stringify(pandatas),
            "memo": "memo"
        };
        //
        console.info(pandatas);
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url: "pans/updatepan",
            data: JSON.stringify(pandata),
            success: function (data) {
                console.info(data);
            }
        });
    }

    PanEditor.prototype.loadeditor = function (options) {
        var that = this;
        $.each(that.controls, function (i, val) {
            $("#" + val.id + "cd").remove();
        })
        that.controls = [];
        //把之前的清除掉
        that.count = 0;

        var data = {
            "panid": options.panid,
        };
        //
        console.info(that.controls);
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url: "pans/getpanbyid",
            data: JSON.stringify(data),
            success: function (data) {
                that.count = data[0].pancount;
                var tmpcontous = JSON.parse(data[0].content)
                console.info(tmpcontous);
                $.each(tmpcontous, function (i, val) {
                    var cchtml = '<div data=\'' + JSON.stringify({
                        "type": val.type
                    }) + '\' id="' + val.id + 'cc" class="dragresize-content"></div>';
                    var jsobj = 'var mypan=new ' + val.type + '(); mypan.init({"id":"' + val.id + 'cc' + '"});';
                    that.createcontrol({
                        "id": val.id,
                        "type": val.type,
                        "html": cchtml,
                        "jsobj": jsobj,
                        "data": val.content,
                        "left": val.postion.left,
                        "top": val.postion.top,
                        "width": val.postion.width,
                        "height": val.postion.height,
                        "zindex": val.zindex
                    });
                    //初始化执行脚本
                });
            }
        });
    }

    PanEditor.prototype.createshow = function (options) {

    }

    PanEditor.prototype.createcontrol = function (options) {
        var that = this;

        //拖拽边框样式
        var style = 'left:' + options.left + ';top:' + options.top + ';width:' + options.width + ';height:' + options.height +
            ';background:transparent; text-align: center;z-index:' + options.zindex;

        var _daragdiv = '<div id="' + options.id + 'cd" data=\'{"id":"' + options.id +
            'cd"}\' class="drsElement drsMoveHandle" style="' + style + '">' + options.html + '</div>';
        var dragdiv = $(_daragdiv);
        //内容对象
        var contentdiv = dragdiv.find("#" + options.id + "cc");


        $("#workcenter").append(dragdiv);
        //初始化对象内容        
        eval(options.jsobj);
        //添加到列表对象
        that.controls.push({
            "id": options.id,
            "type": options.type,
            "content": options.data,
            "zindex": options.zindex,
            "tclass": mypan
        });
        console.info(that.controls);

        that.dragresize.resizeHandleSet(dragdiv[0], true);
        //删除对象
        $("#" + options.id + "cd").find(".dragresize-remove").on("click", function (e) {
            $("#" + options.id + "cd").remove();
            //从列表删除
            var i = _.findIndex(that.controls, {
                "id": options.id
            });
            //移除当前的空间
            that.controls.splice(i, 1);
        });
        //置于顶层layerfirst
        $("#" + options.id + "cd").find(".dragresize-lf").on("click", function (e) {
            var zindex = $(this).parent().css("z-index");
            that.changezindex(zindex, 999);
        });
        //置于底层layerlast
        $("#" + options.id + "cd").find(".dragresize-ll").on("click", function (e) {
            var zindex = $(this).parent().css("z-index");
            that.changezindex(zindex, 0);
        });
        //置于上一层layertop
        $("#" + options.id + "cd").find(".dragresize-lt").on("click", function (e) {
            var zindex = $(this).parent().css("z-index");
            that.changezindex(zindex, 1);
        });
        //置于下一层layerbottom
        $("#" + options.id + "cd").find(".dragresize-lb").on("click", function (e) {
            var zindex = $(this).parent().css("z-index");
            that.changezindex(zindex, -1);
        });
    }
    PanEditor.prototype.initdrag = function (options) {
        var that = this;
        $(".draglist").on("dragstart", function (e) {
            console.info(e);
        });

        $(".draglist").on("dragend", function (e) {
            console.info(e.target);
            that.count++;
            var data = JSON.parse($(e.target).attr("data"));

            var x = (e.originalEvent.offsetX - 200);
            var y = e.originalEvent.offsetY + 50;
            var id = "vpc" + that.count;

            var cchtml = '<div data=\'' + JSON.stringify(data) + '\' id="' + id + 'cc" class="dragresize-content"></div>';
            var jsobj = 'var mypan=new ' + data.type + '(); mypan.init({"id":"' + id + 'cc' + '"});';

            that.createcontrol({
                "id": id,
                "type": data.type,
                "html": cchtml,
                "jsobj": jsobj,
                "data": {},
                "left": x + "px",
                "top": y + "px",
                "width": "504px",
                "height": "340px",
                "zindex": that.controls.length,
            });
        });
    }

    PanEditor.prototype.setzoom = function (zoomNum) {
        //设置真正工作区比例

        var $box = $(".workbox");
        var $boxin = $('.workCenter');
        var boxH = $box.height();
        var boxInW = 1920 * zoomNum;
        var boxInH = 1080 * zoomNum;
        var cH = 0;
        if (boxH > boxInH) {
            cH = (boxH - boxInH);
            //$boxin.css({padding:0});
        } else {
            cH = 0;
            //$boxin.css({padding:'10px'});
        }

        //$boxin.animate({zoom:zoomNum,left:'50%',top:'50%',marginLeft:-W/2,marginTop:-H/2});
        $boxin.css({ zoom: zoomNum, marginTop: cH });

    }
    /*
    构建右边的界面，方便绑定

    */
    PanEditor.prototype.createtools = function (options) {
        var htmls = "";
        $.each(options, function (i, val) {
            htmls += "" + val.title + "<input type='" + val.input + "' v-model='" + val.databing+"' >";
        });
        return htmls;
    }
    PanEditor.prototype.uploadcanvas = function () {
        var that = this;
        var str = $('#workcenter');
        //console.log(str);  
        html2canvas([str.get(0)], {
            onrendered: function (canvas) {

                var extra_canvas = document.createElement("canvas");
                extra_canvas.setAttribute('width', 768);
                extra_canvas.setAttribute('height', 432);
                var ctx = extra_canvas.getContext('2d');
                ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 768, 432);

                var image = extra_canvas.toDataURL("image/png");
                $("#imgtitleimg").attr("src", image);
                //并将图片上传到服务器用作图片分享  
                $.ajax({
                    type: "POST",
                    url: 'pans/uploadcanvas',
                    data: { "panid": that.panid, "imgdata": image },
                    timeout: 6000,
                    success: function (data) {
                        console.info("end!");
                    }
                });
            }
        });
    }
    /*
    改变组件的的顺序
    1：最顶层
    2：最底层
    3：向上一层
    4：向下一层
    */
    PanEditor.prototype.changezindex = function (indexold, indexnew) {
        // indexnew == 0;//底层
        //  indexnew == 999;//顶层
        //  indexednew == 1;//上移
        //  indexnew == -1;//下移
        var that = this;


        if (indexnew === 0) {
            var removed = that.controls.splice(indexold, 1);
            var insert = that.controls.splice(0, 0, removed); //从第0个位置开始插入 
        } else if (indexnew === 999) {
            var removed = that.controls.splice(indexold, 1);
            var insert = that.controls.push(removed); //从第0个位置开始插入 
        } else if (indexnew === 1) {
            var t = that.controls[indexold];
            that.controls[indexold] = that.controls[indexold + 1];
            that.controls[indexold + 1] = t;
        }
        else if (indexnew === -1) {
            var t = that.controls[indexold];
            that.controls[indexold] = that.controls[indexold - 1];
            that.controls[indexold - 1] = t;
        }
        //重新排序
        $.each(that.controls, function (i, val) {
            $("#" + val.id + "cd").css("z-index", i);
        });


    }
    // 返回
    return PanEditor;
})();

var paneditor;
$(function () {
    var panid = getquery("panid", location.href);
    var tempid = getquery("tempid", location.href);
    paneditor = new PanEditor({ "panid": panid, "tempid": tempid });

})